package person.wend.javalearnexample.util.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFutureTest();
        FutureTaskTest();
    }

    public static void CompletableFutureTest() {
        // 使用CompletableFuture
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello from CompletableFuture";
        });

        // 注册回调函数，当CompletableFuture完成时执行
        completableFuture.thenAccept(result -> System.out.println("Result from CompletableFuture: " + result));

        // 等待CompletableFuture完成
        completableFuture.join();
    }

    public static void FutureTaskTest() throws ExecutionException, InterruptedException{
        // 使用FutureTask
        Callable<Integer> callable = () -> {
            Thread.sleep(2000);
            return 42;
        };
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask);
        thread.start();

        // 获取FutureTask的结果（会阻塞直到任务完成）
        Integer resultFromFutureTask = futureTask.get();
        System.out.println("Result from FutureTask: " + resultFromFutureTask);
    }
}
